from csv import reader
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from pylab import mpl
from tkinter import *
import tkinter.messagebox   # 导入tkinter.messagebox模块。
from PIL import Image, ImageTk

# 《这是一个不存在的文件名》
# Yearly mean total sunspot number (1900 - now).csv

# 1.GUI整体框架(背景图与几个大标题)
top = Tk()  # Tk构造器
top.geometry()
# top.geometry('470x539')  # 指定窗口大小，宽度x高度
top.title("本地简单数据分析平台")
# 背景画布
canvas = Canvas(top, width=500, height=600, bg='white')
image = Image.open("花草.jpg").resize((900, 1000))
im = ImageTk.PhotoImage(image)
canvas.create_image(180, 350, image=im)  # 使用create_image将图片添加到Canvas组件中
canvas.grid_configure(row=1, column=1, rowspan=15, columnspan=5)
# 导入提示文字标签
NameLabel = Label(top, text='请输入文件名：', font=("楷体", 12, 'bold'), height=2, relief="groove", bg='white')
NameText = Text(top, height=1.6, width=33)
# 几个模块的标题+两个留白部分
label_file = Label(top, text='文件基本信息：', font=("楷体", 12, 'bold'), height=2, relief="groove", bg='white')
label_list = Label(top, text='数据表格显示：', font=("楷体", 12, 'bold'), height=2, relief="groove", bg='white')
label_top = Label(top, text="基础数据分析：", font=("楷体", 12, 'bold'), height=2, relief="groove", bg='white')
label_chart = Label(top, text="图像分析预览与保存：", font=("楷体", 12, 'bold'), height=2, relief="groove", bg='white')
frame = Frame(top, bg="white", bd=20, height=120, width=420, borderwidth=2, relief="groove")
frame2 = Frame(top, bg="white", bd=20, height=200, width=180, borderwidth=2, relief="groove")


# 2.导入CSV文件
# 变量名初始化
the_mean = -1  # 平均值
the_median = -1  # 中位数
the_mode = -1  # 众数
a = ''  # 第一列的表头
b = ''  # 第二列的表头
Alist = []  # 第一列数据
Blist = []  # 第二列数据
n = 0  # 数据行数
flag = ''  # 储存文件名 用作判断条件
LisBox = Listbox()  # 列表框架部件
scr = Scrollbar()  # 滚动条部件
filename = ''  # 文件名
# 导入按钮
open_button = Button(top, text='导入文件', font=("楷体", 12, 'bold'), bg='beige', cursor='hand2', command=lambda: OpenBut())

# 导入函数
def OpenBut():
    global the_median, the_mean, the_mode, a, b, Alist, Blist, n, flag, LisBox, scr, filename
    # filename = "Yearly mean total sunspot number (1900 - now).csv"
    # filename = "Yearly mean total sunspot number (1700 - now).csv"
    # filename = "Yearly mean total sunspot number (1700 - 1800).csv"
    filename = NameText.get(1.0, END)[:-1:]  # 获得t的从1.0位置到末尾的文本

    if filename == '':
        tkinter.messagebox.showerror("文件名为空", "请输入文件名！")
    elif filename == flag:
        tkinter.messagebox.showerror("文件已导入", "请不要重复导入同一个文件！")
    elif filename != '':
        try:
            with open(filename, "rt") as raw_data:
                readers = reader(raw_data, delimiter=",")
                x = list(readers)
                a, b = x.pop(0)  # a是年份，b是太阳黑子数
                print(x)
                data = np.array(x).astype("float")
                n, m = data.shape  # n行数，m列数

                Alist = [int(data[i][0]) for i in range(n)]  # 年份列表
                Blist = [data[j][1] for j in range(n)]  # 黑子数列表

                # 文件基本信息
                name_label = Label(top, text='文件名为：'+filename, anchor="center", bg='white')
                x_label = Label(top, text='自变量x为：'+a, anchor="center", bg='white')
                y_label = Label(top, text='因变量y为：'+b, anchor="center", bg='white')
                n_label = Label(top, text='文件总行数：'+str(n+1), anchor="center", bg='white')
                m_label = Label(top, text='文件总列数：'+str(m), anchor="center", bg='white')
                name_label.grid_configure(row=3, column=1, rowspan=1, columnspan=4)
                x_label.grid_configure(row=4, column=1, rowspan=1, columnspan=2)
                y_label.grid_configure(row=4, column=3, rowspan=1, columnspan=2)
                n_label.grid_configure(row=5, column=1, rowspan=1, columnspan=2)
                m_label.grid_configure(row=5, column=3, rowspan=1, columnspan=2)

                # 表格展示
                # 删除之前控件
                if flag != "":
                    LisBox.destroy()
                    scr.destroy()
                scr = Scrollbar(frame2)
                scr.pack(side=RIGHT, fill=Y)
                LisBox = Listbox(frame2, yscrollcommand=scr.set)
                LisBox.insert('end', a + "  | " + b)
                for i in range(n):
                    LisBox.insert("end", str(Alist[i]) + " | " + str(Blist[i]))
                LisBox.pack(side=LEFT)
                scr.config(command=LisBox.yview)

                flag = filename
        # 异常处理
        except FileNotFoundError:
            print("未找到文件!\n本目录下未找到此文件，请输入正确文件名！")
            tkinter.messagebox.showerror("未找到文件", "本目录下未找到此文件，请输入正确文件名！")

